#include "head.h"

#include <stdio.h>
#include <string.h>
#include <ctype.h>

char* removeTrailingNewline(char* str) {
    int len = strlen(str);
    if (len > 0 && (str[len-1] == '\n' || str[len-1] == '\r')) {
        str[len-1] = '\0'; // 如果最后一个字符是'\n'或'\r'，将其替换为字符串终止符
    }
    return str;
}

int analyze_cmd(int net_fd, char *str, request_t * request){

        // 清除后面的空格
        char* arg = removeTrailingNewline(str);
        char * cmd = strtok(arg," ");
        //以空格符作为分隔        
        if(cmd == NULL){
            printf("Error :Command missing\n");
            return 1;
        }
        //获取下一个参数
        char * token = strtok(NULL," ");

        printf("cmd = %s, arg = %s\n", cmd, token);



        int ret;
        if(strcmp(cmd,"cd")==0){
            request->flag = CD;
            printf("flag = CD\n");
            ret = net_cd(net_fd,token,request);
        }else if(strcmp(cmd,"ls")==0){
            printf("flag = LS\n");
            request->flag = LS;
            ret = net_ls(net_fd, request);
        }else if(strcmp(cmd,"puts")==0){
            printf("flag = PUTS\n");
            request->flag = PUTS;
            ret = net_puts(net_fd,token,request);
        }else if(strcmp(cmd,"gets")==0){
            printf("flag = GETS\n");
            request->flag = GETS;
            ret = net_gets(net_fd,token, request);
        }else if(strcmp(cmd,"rm")==0){
            printf("flag = RM\n");
            request->flag = RM;
            ret = net_rm(net_fd, token, request);
        }else if(strcmp(cmd,"pwd")==0){
            printf("flag = PWD\n");
            request->flag = PWD;
            ret = net_pwd(net_fd,request);
        }else if(strcmp(cmd,"mkdir")==0){
            printf("flag = MKDIR\n");
            request->flag = MKDIR;
            ret = net_mkdir(net_fd, token,  request);
        }else if(strcmp(cmd,"exit")==0){
            return 2; // 正常退出
        }else{
            printf("aaa\n");
            return 1; // 未识别的命令，返回错误
        }

        if(ret == -1){
            return -1;
        }
    return 0;
}



